<?php
/**
 * Created by IntelliJ IDEA.
 * User: kha
 * Date: 10/4/13
 * Time: 8:56 PM
 * To change this template use File | Settings | File Templates.
 */

// TODO: Kha

/**
 * Request a SVN repo for group
 */

// Get the group guid
$group_guid = (int)get_input('group_guid');

//register_error(elgg_echo('group:notdeleted'));

// Check if there already is a repo for this group
// 1. Dirty way:
// Check the dir in /opt/usersvn/repositories whose name equal to the group's id

// linux shell command to execute
$exec = 'find /opt/ubersvn/repositories -type d -name ' . $group_guid;

// execute the cmd and get output
$output = shell_exec($exec);
//system_message($output);
// process the output
// empty => not found => request to the SVN operator (inbox message) => system message
// not empty => found => already request and proceeded => system message.

if (!$output) {

    //send message to SVN Manager (svnadmin)
    $svnadmin_username = 'svnadmin';
    $user_svnadmin = get_user_by_username($svnadmin_username);

    // check the svn user exists
    if (!$user_svnadmin) {
        register_error(elgg_echo("messages:user:nonexist"));
    }

    // compose the mesage
    // subject
    $subject = elgg_echo('groups:svn_request_message_title');

    // body
    $body = elgg_echo('groups:svn_request_message', array($group_guid));
    $body .= elgg_list_entities_from_relationship(array(
        'relationship' => 'member',
        'relationship_guid' => $group_guid,
        'inverse_relationship' => true,
        'types' => 'user',
        'limit' => 12,
        'pagination' => false,
        'list_type' => 'gallery',
        'gallery_class' => 'elgg-gallery-users',
        'pagination' => false));
    // reply
    // get current user
    $user = elgg_get_logged_in_user_entity();
    $from =  $user->guid;
    // send it
    $result = messages_send($subject, $body, $user_svnadmin->guid, $from);

    // check the sending
    if (!$result) {
        register_error(elgg_echo("messages:error"));
    }

    system_message(elgg_echo('groups:svn_request_success'));

    forward(REFERER);
}

system_message(elgg_echo('groups:svn_request_already', array($group_guid)));


// 2. Optimized way: Check there is an annotation for this group that have the id 'group_repo_created' => Hard way
